import json
import csv
import time


def save_items(func):
    def wapper(*args, save=False):
        movie_list = func(*args, save=False)
        if save is False:
            return movie_list
        if save is True:
            action_id = input("选择保存方式:1,TXT格式 | 2,Excel格式 | 3,json格式 :")
            save_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
            if action_id == "1":
                with open('movie_data_%s.txt' % save_time, 'w')as file:
                    i = 0
                    for movie in movie_list:
                        i += 1
                        title = "电影%s: " % i + movie.title + "\n"
                        download_links = "链接: " + movie.download_links[0] + "\n"
                        file.write(title + download_links)
            elif action_id == "2":
                movie_data_list = []
                i = 0
                for movie in movie_list:
                    i += 1
                    title = "电影%s: " % i + movie.title + "\n"
                    download_links = "电影%s链接: " % i + movie.download_links[0] + "\n"
                    movie_data_list.append([title])
                    movie_data_list.append([download_links])
                with open('movie_data_%s.csv' % save_time, 'w')as file:
                    writer = csv.writer(file)
                    writer.writerow(["电影名称", "链接"])
                    writer.writerows(movie_data_list)
            elif action_id == "3":
                movie_dict = {}
                i = 0
                for movie in movie_list:
                    i += 1
                    movie_dict['电影_%s' % i] = movie.title
                    movie_dict['电影_%s链接' % i] = movie.download_links[0]
                    json.dump(movie_dict, open("movie_data_%s.json" % save_time, "w"))
            else:
                print("保存方式错误")
                return movie_list
            print("保存成功")
            return movie_list

    return wapper
